package com.qf.util;


import com.qf.bean.Employee;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ResourceBundle;

/**
 * 2019/11/25
 * Administrator
 * ssm1119
 * 面向对象面向君  不负代码不负卿
 */
public class LoginInterceptor implements HandlerInterceptor {


    @Override   //拦截器开始执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否是匿名地址(用户在未登录的情况下可以访问的资源称为匿名地址)
        //读取属性文件中的信息
        ResourceBundle anon = ResourceBundle.getBundle("anon");//只需要指定文件名，不要写文件后缀
        String requestURI = request.getRequestURI();//请求地址
        if(anon.containsKey(requestURI)){
            //是匿名地址
            return  true;
        }
        //2.判断session是否有值
        HttpSession session = request.getSession();
        Employee user = (Employee) session.getAttribute("user");
        if(user!=null){
            return  true;
        }else{
            //3.根据结果跳转页面
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print("<script>alert('请登录');location.href='/login.jsp'</script>");
            return false;
        }

    }

    @Override  //拦截器结束执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override  //无论是否有异常都要执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
